<?php
namespace App\Admin\Controllers\SalesReport;

use App\Admin\Ajax\SalesReport\MonthlyAjax;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysIArea;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use App\Models\SalesReport\MonthlyCTarget;
use App\Models\SalesReport\MonthlyCv;
use App\Util\SVPermission;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class MonthlyCVController extends AdminController{

    protected $title = '品类月销量和月目标';

    protected $filters = [
        'season' => null,
        'classify_id' => null,
        'report_status' => null,
        'plat_id' => null,
        'area_id' => null,
        'country_id' => null,
        'seller_id' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $headers = MonthlyCv::headersField();
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query,$headers);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['report_status'] = getOptions(ProductClassify::$_reportStatus+['3' => 'All'],$this->filters['report_status']);
        $filtersBlade['plat_id'] = getOptions(SysPlat::options(),$this->filters['plat_id']);
        $filtersBlade['area_id'] = getOptions(SysIArea::options(),$this->filters['area_id']);
        $filtersBlade['country_id'] = getOptions(AmazonCountry::options(),$this->filters['country_id']);
        $filtersBlade['seller_id'] = getOptions(User::getSellerOptions(),$this->filters['seller_id']);

        $downloadUrl = '/xqc/sales-report/monthly-cv-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('sales-report.monthly-cv.index', compact('paginator','total','headers','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            if($field == 'report_status'){
                $filters[$field] = request('report_status') ?? 1;
            }else{
                $filters[$field] = request($field);
            }
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = MonthlyCv::query();
        $query = SVPermission::area($query);
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'season'){
                $query->whereHas('classify', function ($query) use($filter){
                    $query->where('season', $filter);
                });
            }
            if($field == 'report_status' && $filter != 3){
                $query->whereHas('classify', function ($query) use($filter){
                    $query->where('report_status', $filter);
                });
            }
            if(in_array($field,['classify_id','plat_id','area_id','country_id','seller_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function _sum($query,$headers){
        $sum = $query->selectRaw($this->__getSumFields($headers))->groupBy(1)->first();
        return $sum ? $sum->toArray() : $this->__getSumFieldsInit($headers);
    }

    private function __getSumFields($headers){
        $re = '';
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re .= 'sum('.$field.') as '.$field.',';
            }else{
                continue;
            }
        }
        return $re.'1';
    }

    private function __getSumFieldsInit($headers){
        $re = [];
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re[$field] = null;
            }else{
                continue;
            }
        }
        return $re;
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $title1 = ['平台','站点','国家','销售','季节性','品类'];
        $title2 = [];
        for($i = MonthlyCv::V_NUM - 1; $i >= 0; $i--){
            $thisTime = strtotime(date('Y-m-01') . "-$i month");
            $title2[] = date("y/m",$thisTime).'销量';
            $title2[] = date("y/m",$thisTime).'目标值';
            $title2[] = date("y/m",$thisTime).'完成率';
        }
        $title3 = [];
        $endTime = strtotime(MonthlyCTarget::END_DATE);
        for($i = 1; $i <= MonthlyCTarget::E_NUM - 1; $i++){
            $_thisTime = strtotime(date('Y-m-01') . "+$i month");
            if($_thisTime > $endTime)break;
            $title3[] = date("y/m",$_thisTime).'目标值';
        }
        $head = array_merge($title1,$title2,$title3);
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="（平台）品类月销量和月目标.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(500, function ($re) use ($fp){
                $data = MonthlyCv::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new MonthlyAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new MonthlyAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }
}
